'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { z } from 'zod';
import { useForm, Controller } from 'react-hook-form';
import type { Control, ControllerRenderProps, FieldValues, Path } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { format } from 'date-fns';
import { zhCN } from 'date-fns/locale';
import { useToast } from '@/components/ui/use-toast';
import { Toaster } from 'sonner';
import { Calendar } from '@/components/ui/calendar';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { cn } from '@/lib/utils';
import { CalendarIcon, Pencil, Trash } from 'lucide-react';
import { formatDate } from '@/lib/utils';

import {
  Student as StudentType,
  StudentQueryParams,
  getStudents,
  createStudent,
  updateStudent,
  deleteStudent,
  CreateStudentParams,
  UpdateStudentParams,
  PageResponse
} from '@/services/studentService';
import { getClassList } from '@/services/classService';
import { getAllParents } from '@/services/parentService';

import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog';
import {
  Form,
  FormControl,
  FormField as FormFieldUI,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Switch } from '@/components/ui/switch';
import { FadeIn } from '@/components/ui/motion';
import { CheckCircle, XCircle, RefreshCw } from 'lucide-react';

// 添加自定义样式
const calendarStyles = `
  .rdp-caption {
    display: flex;
    justify-content: center;
    padding: 0.5rem;
  }
  
  .rdp-month {
    width: 100%;
  }
  
  .rdp-table {
    width: 100%;
    border-collapse: collapse;
  }
  
  .rdp-head_cell {
    text-align: center;
    padding: 0.5rem;
    font-size: 0.875rem;
    font-weight: 500;
  }
  
  .rdp-cell {
    text-align: center;
    padding: 0;
  }
  
  .rdp-day {
    width: 2.25rem;
    height: 2.25rem;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 9999px;
  }
  
  .rdp-day_selected {
    background-color: hsl(var(--primary));
    color: hsl(var(--primary-foreground));
  }
  
  .rdp-day_today {
    background-color: hsl(var(--accent));
    color: hsl(var(--accent-foreground));
  }
  
  .rdp-nav {
    display: none;
  }
`;

// 表单字段类型
interface FormFieldProps<T extends FieldValues = StudentFormValues> {
  control: Control<T>;
  name: Path<T>;
  [key: string]: any;
}

interface ClassInfo {
  id: number;
  name: string;
  grade: string;
  teacher: string;
}

interface ParentInfo {
  id: number;
  name: string;
  phone: string;
  email: string;
}

type Student = StudentType;

interface ClassListItem {
  id: number;
  grade: string;
  name: string;
  teacherName: string;
}

interface ParentListItem {
  id: number;
  name: string;
  phone: string;
}

// 学生表单验证模式
const studentFormSchema = z.object({
  name: z.string().min(2, "姓名至少2个字符").max(50, "姓名最多50个字符"),
  gender: z.enum(["男", "女"], {
    required_error: "请选择性别",
  }),
  birthday: z.date().optional(),
  classId: z.number().optional(),
  parentId: z.number().optional(),
});

type StudentFormValues = z.infer<typeof studentFormSchema>;

// 表单字段组件
const FormField = <T extends FieldValues>({ control, name, ...props }: FormFieldProps<T>) => {
  return (
    <FormControl>
      <Controller
        control={control}
        name={name}
        render={({ field }: { field: ControllerRenderProps<T, typeof name> }) => (
          <Input {...field} {...props} />
        )}
      />
    </FormControl>
  );
};

export default function StudentsPage() {
  const router = useRouter();
  const { toast } = useToast();
  const [students, setStudents] = useState<Student[]>([]);
  const [classes, setClasses] = useState<ClassListItem[]>([]);
  const [parents, setParents] = useState<ParentListItem[]>([]);
  const [searchTerm, setSearchTerm] = useState('');
  const [loading, setLoading] = useState(false);
  const [isAddDialogOpen, setIsAddDialogOpen] = useState(false);
  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
  const [selectedStudent, setSelectedStudent] = useState<Student | null>(null);
  const [pagination, setPagination] = useState({
    page: 0,
    size: 10,
    totalPages: 0,
    totalElements: 0,
    last: true,
    first: true
  });

  // 添加学生表单
  const addForm = useForm<StudentFormValues>({
    resolver: zodResolver(studentFormSchema),
    defaultValues: {
      name: '',
      gender: undefined,
      birthday: undefined,
      classId: undefined,
      parentId: undefined,
    },
  });

  // 编辑学生表单
  const editForm = useForm<StudentFormValues>({
    resolver: zodResolver(studentFormSchema),
    defaultValues: {
      name: '',
      gender: undefined,
      birthday: undefined,
      classId: undefined,
      parentId: undefined,
    },
  });

  // 获取班级和家长列表
  useEffect(() => {
    const fetchData = async () => {
      try {
        const [classesData, parentsData] = await Promise.all([
          getClassList(),
          getAllParents()
        ]);
        console.log('班级数据:', classesData);
        console.log('家长数据:', parentsData);
        
        // 处理班级数据
        if (Array.isArray(classesData)) {
          // 如果是数组，直接使用
          setClasses(classesData.map(cls => ({
            id: cls.id,
            grade: cls.grade || '',
            name: cls.name || '',
            teacherName: cls.teacherName || ''
          })));
        } else if (classesData && typeof classesData === 'object') {
          // 如果是对象，尝试提取数据
          console.log('班级数据是对象，尝试提取:', classesData);
          const classArray = Array.isArray((classesData as any).data) 
            ? (classesData as any).data 
            : Array.isArray((classesData as any).content) 
              ? (classesData as any).content 
              : [];
          
          setClasses(classArray.map((cls: any) => ({
            id: cls.id,
            grade: cls.grade || '',
            name: cls.name || '',
            teacherName: cls.teacherName || (cls.teacher ? cls.teacher.name : '') || ''
          })));
        } else {
          setClasses([]);
        }
        
        setParents(parentsData || []);
      } catch (error) {
        console.error('获取班级和家长列表失败:', error);
        toast({
          title: '加载失败',
          description: '无法获取班级和家长列表，请稍后重试',
          variant: 'destructive',
        });
      }
    };
    fetchData();
  }, []);

  // 初始加载
  useEffect(() => {
    fetchStudents();
  }, []);

  // 获取学生列表
  const fetchStudents = async (params: StudentQueryParams = {}) => {
    setLoading(true);
    try {
      const { page = pagination.page, size = pagination.size, keyword = searchTerm, classId, parentId } = params;
      const response = await getStudents({ page, size, keyword, classId, parentId });
      
      // 检查响应数据结构
      console.log('API 响应:', response);
      
      // 处理API返回的数据结构
      if (response?.content) {
        // 设置学生列表和分页数据
        setStudents(response.content);
        setPagination({
          page: response.pageable.pageNumber,
          size: response.pageable.pageSize,
          totalPages: response.totalPages,
          totalElements: response.totalElements,
          last: response.last,
          first: response.first
        });
      } else {
        console.error('API响应数据格式错误');
        toast({
          title: '数据格式错误',
          description: '服务器返回的数据格式不正确',
          variant: 'destructive',
        });
        setStudents([]);
      }
    } catch (error) {
      console.error('获取学生列表失败:', error);
      toast({
        title: '获取失败',
        description: '无法获取学生列表，请稍后重试',
        variant: 'destructive',
      });
      // 出错时设置空数据
      setStudents([]);
    } finally {
      setLoading(false);
    }
  };

  // 搜索处理
  const handleSearch = () => {
    fetchStudents({ page: 0, keyword: searchTerm });
  };

  // 分页处理
  const handlePageChange = (newPage: number) => {
    fetchStudents({ page: newPage });
  };

  // 添加学生
  const handleAddStudent = async (data: StudentFormValues) => {
    setLoading(true);
    try {
      console.log('提交的表单数据:', data);
      
      // 转换日期格式
      const formattedData = {
        ...data,
        birthday: data.birthday ? format(data.birthday, 'yyyy-MM-dd') : undefined,
      };
      
      // 创建学生参数
      const createParams: CreateStudentParams = {
        name: formattedData.name,
        gender: formattedData.gender,
        birthday: formattedData.birthday,
        classId: formattedData.classId !== undefined ? Number(formattedData.classId) : undefined,
        parentId: formattedData.parentId !== undefined ? Number(formattedData.parentId) : undefined,
        enabled: true // 默认启用
      };
      
      console.log('创建参数:', createParams);
      
      const result = await createStudent(createParams);
      
      console.log('添加学生结果:', result);
      
      // 刷新列表
      fetchStudents();
      
      // 关闭对话框并重置表单
      setIsAddDialogOpen(false);
      addForm.reset();
      
      toast({
        title: '添加成功',
        description: `学生 ${data.name} 已成功添加`,
      });
    } catch (error) {
      console.error('添加学生失败:', error);
      toast({
        title: '添加失败',
        description: '学生添加失败，请稍后重试',
        variant: 'destructive',
      });
    } finally {
      setLoading(false);
    }
  };

  // 编辑学生
  const handleEditStudent = async (data: StudentFormValues) => {
    if (!selectedStudent) return;
    
    setLoading(true);
    try {
      console.log('提交的编辑表单数据:', data);
      
      // 转换日期格式
      const formattedData = {
        ...data,
        birthday: data.birthday ? format(data.birthday, 'yyyy-MM-dd') : undefined,
      };
      
      // 确保包含原有的班级ID和家长ID
      const updateParams: UpdateStudentParams = {
        name: formattedData.name,
        gender: formattedData.gender,
        birthday: formattedData.birthday,
        classId: formattedData.classId !== undefined ? Number(formattedData.classId) : selectedStudent.classInfo?.id,
        parentId: formattedData.parentId !== undefined ? Number(formattedData.parentId) : selectedStudent.parent?.id,
      };
      
      console.log('更新参数:', updateParams);
      
      const result = await updateStudent(selectedStudent.id, updateParams);
      
      console.log('编辑学生结果:', result);
      
      // 刷新列表
      fetchStudents();
      
      // 关闭对话框
      setIsEditDialogOpen(false);
      
      toast({
        title: '更新成功',
        description: `学生 ${data.name} 信息已更新`,
      });
    } catch (error) {
      console.error('编辑学生失败:', error);
      toast({
        title: '更新失败',
        description: '学生信息更新失败，请稍后重试',
        variant: 'destructive',
      });
    } finally {
      setLoading(false);
    }
  };

  // 删除学生
  const handleDeleteStudent = async () => {
    if (!selectedStudent) return;
    
    setLoading(true);
    try {
      await deleteStudent(selectedStudent.id);
      
      // 刷新列表
      fetchStudents();
      
      // 关闭对话框
      setIsDeleteDialogOpen(false);
      
      toast({
        title: '删除成功',
        description: `学生 ${selectedStudent.name} 已删除`,
      });
    } catch (error) {
      console.error('删除学生失败:', error);
      toast({
        title: '删除失败',
        description: '学生删除失败，请稍后重试',
        variant: 'destructive',
      });
    } finally {
      setLoading(false);
    }
  };

  // 打开编辑对话框
  const openEditDialog = (student: Student) => {
    setSelectedStudent(student);
    
    console.log('编辑学生信息:', student);
    
    // 设置表单默认值
    editForm.reset({
      name: student.name,
      gender: student.gender as "男" | "女",
      birthday: student.birthDate ? new Date(student.birthDate) : undefined,
      classId: student.classInfo?.id,
      parentId: student.parent?.id,
    });
    
    setIsEditDialogOpen(true);
  };

  // 打开删除对话框
  const openDeleteDialog = (student: Student) => {
    setSelectedStudent(student);
    setIsDeleteDialogOpen(true);
  };

  // 打开添加对话框
  const openAddDialog = () => {
    addForm.reset({
      name: '',
      gender: undefined,
      birthday: undefined,
      classId: undefined,
      parentId: undefined,
    });
    setIsAddDialogOpen(true);
  };

  // 渲染班级选择项
  const renderClassOptions = () => {
    console.log('渲染班级选项:', classes);
    if (!classes || classes.length === 0) {
      return <SelectItem value="no-class" disabled>暂无班级数据</SelectItem>;
    }
    
    return classes.map((cls) => (
      <SelectItem key={cls.id} value={String(cls.id)}>
        {cls.grade}{cls.name} - {cls.teacherName}
      </SelectItem>
    ));
  };
  
  // 渲染家长选择项
  const renderParentOptions = () => {
    console.log('渲染家长选项:', parents);
    if (!parents || parents.length === 0) {
      return <SelectItem value="no-parent" disabled>暂无家长数据</SelectItem>;
    }
    
    return parents.map((parent) => (
      <SelectItem key={parent.id} value={String(parent.id)}>
        {parent.name} ({parent.phone})
      </SelectItem>
    ));
  };

  return (
    <FadeIn>
      <Toaster />
      <style jsx global>{calendarStyles}</style>
      <div className="container mx-auto py-6">
        <h1 className="text-2xl font-bold mb-6">学生管理</h1>
        
        {/* 搜索和添加按钮 */}
        <div className="flex justify-between mb-6">
          <div className="flex gap-2">
            <Input
              placeholder="搜索学生姓名、班级或家长..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="w-64"
              onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
            />
            <Button onClick={handleSearch}>搜索</Button>
          </div>
          <Button onClick={openAddDialog}>
            添加学生
          </Button>
        </div>
        
        {/* 学生列表 */}
        <div className="rounded-md border">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>学号</TableHead>
                <TableHead>姓名</TableHead>
                <TableHead>性别</TableHead>
                <TableHead>出生日期</TableHead>
                <TableHead>班级</TableHead>
                <TableHead>家长</TableHead>
                <TableHead>联系电话</TableHead>
                <TableHead>创建时间</TableHead>
                <TableHead>操作</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {loading ? (
                <TableRow>
                  <TableCell colSpan={9} className="text-center py-10">
                    <RefreshCw className="h-6 w-6 animate-spin mx-auto" />
                    <p className="mt-2 text-sm text-gray-500">加载中...</p>
                  </TableCell>
                </TableRow>
              ) : students.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={9} className="text-center py-4">
                    暂无数据
                  </TableCell>
                </TableRow>
              ) : (
                students.map((student) => (
                  <TableRow key={student.id}>
                    <TableCell>{student.studentNumber || student.id}</TableCell>
                    <TableCell>{student.name}</TableCell>
                    <TableCell>{student.gender}</TableCell>
                    <TableCell>{student.birthDate ? format(new Date(student.birthDate), 'yyyy-MM-dd') : '-'}</TableCell>
                    <TableCell>{student.classInfo ? `${student.classInfo.grade}${student.classInfo.name}` : '-'}</TableCell>
                    <TableCell>{student.parent ? student.parent.name : '-'}</TableCell>
                    <TableCell>{student.parent ? student.parent.phone || '-' : '-'}</TableCell>
                    <TableCell>{formatDate(student.createTime)}</TableCell>
                    <TableCell>
                      <div className="flex gap-2">
                        <Button 
                          variant="outline" 
                          size="sm"
                          onClick={() => openEditDialog(student)}
                        >
                          编辑
                        </Button>
                        <Button 
                          variant="destructive" 
                          size="sm"
                          onClick={() => openDeleteDialog(student)}
                        >
                          删除
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </div>
        
        {/* 分页 */}
        {students.length > 0 && (
          <div className="flex justify-between items-center mt-4">
            <div className="text-sm text-gray-500">
              共 {pagination.totalElements} 条记录，第 {pagination.page + 1}/{pagination.totalPages} 页
            </div>
            <div className="flex gap-2">
              <Button
                variant="outline"
                size="sm"
                onClick={() => handlePageChange(0)}
                disabled={pagination.first}
              >
                首页
              </Button>
              <Button
                variant="outline"
                size="sm"
                onClick={() => handlePageChange(pagination.page - 1)}
                disabled={pagination.first}
              >
                上一页
              </Button>
              <Button
                variant="outline"
                size="sm"
                onClick={() => handlePageChange(pagination.page + 1)}
                disabled={pagination.last}
              >
                下一页
              </Button>
              <Button
                variant="outline"
                size="sm"
                onClick={() => handlePageChange(pagination.totalPages - 1)}
                disabled={pagination.last}
              >
                末页
              </Button>
            </div>
          </div>
        )}
        
        {/* 添加学生对话框 */}
        <Dialog open={isAddDialogOpen} onOpenChange={setIsAddDialogOpen}>
          <DialogContent className="sm:max-w-[500px]">
            <DialogHeader>
              <DialogTitle>添加学生</DialogTitle>
              <DialogDescription>
                请填写学生信息，带 * 为必填项
              </DialogDescription>
            </DialogHeader>
            
            <Form {...addForm}>
              <form onSubmit={addForm.handleSubmit(handleAddStudent)} className="space-y-4">
                <FormFieldUI
                  control={addForm.control}
                  name="name"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>姓名 *</FormLabel>
                      <FormControl>
                        <Input {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                
                <FormFieldUI
                  control={addForm.control}
                  name="gender"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>性别 *</FormLabel>
                      <Select
                        onValueChange={field.onChange}
                        defaultValue={field.value}
                      >
                        <FormControl>
                          <SelectTrigger>
                            <SelectValue placeholder="选择性别" />
                          </SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          <SelectItem value="男">男</SelectItem>
                          <SelectItem value="女">女</SelectItem>
                        </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                
                <FormFieldUI
                  control={addForm.control}
                  name="birthday"
                  render={({ field }) => (
                    <FormItem className="flex flex-col">
                      <FormLabel>出生日期</FormLabel>
                      <Popover>
                        <PopoverTrigger asChild>
                          <FormControl>
                            <Button
                              variant={"outline"}
                              className={cn(
                                "w-full pl-3 text-left font-normal",
                                !field.value && "text-muted-foreground"
                              )}
                            >
                              {field.value ? (
                                format(field.value, "yyyy年MM月dd日", { locale: zhCN })
                              ) : (
                                <span>选择出生日期</span>
                              )}
                              <CalendarIcon className="ml-auto h-4 w-4 opacity-50" />
                            </Button>
                          </FormControl>
                        </PopoverTrigger>
                        <PopoverContent className="w-auto p-0" align="start">
                          <div className="p-3">
                            <Calendar
                              mode="single"
                              selected={field.value}
                              onSelect={field.onChange}
                              disabled={(date) =>
                                date > new Date() || date < new Date("1900-01-01")
                              }
                              initialFocus
                              locale={zhCN}
                              captionLayout="dropdown"
                              fromYear={1900}
                              toYear={new Date().getFullYear()}
                              ISOWeek
                              classNames={{
                                caption_label: "text-sm font-medium",
                                table: "w-full border-collapse space-y-1",
                                head_row: "flex",
                                head_cell: "text-muted-foreground rounded-md w-9 font-normal text-[0.8rem]",
                                row: "flex w-full mt-2",
                                cell: "h-9 w-9 text-center text-sm p-0 relative [&:has([aria-selected])]:bg-accent first:[&:has([aria-selected])]:rounded-l-md last:[&:has([aria-selected])]:rounded-r-md focus-within:relative focus-within:z-20",
                                day: "h-9 w-9 p-0 font-normal aria-selected:opacity-100 rounded-md",
                                day_selected: "bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground focus:bg-primary focus:text-primary-foreground",
                                day_today: "bg-accent text-accent-foreground",
                                day_disabled: "text-muted-foreground opacity-50",
                                day_range_middle: "aria-selected:bg-accent aria-selected:text-accent-foreground",
                                day_hidden: "invisible",
                                nav: "hidden",
                                nav_button: "hidden",
                                nav_button_previous: "hidden",
                                nav_button_next: "hidden",
                              }}
                            />
                          </div>
                        </PopoverContent>
                      </Popover>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormFieldUI
                  control={addForm.control}
                  name="classId"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>班级</FormLabel>
                      <Select
                        onValueChange={(value) => field.onChange(value ? Number(value) : undefined)}
                        value={field.value ? String(field.value) : undefined}
                      >
                        <FormControl>
                          <SelectTrigger>
                            <SelectValue placeholder="选择班级" />
                          </SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          {renderClassOptions()}
                        </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormFieldUI
                  control={addForm.control}
                  name="parentId"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>家长</FormLabel>
                      <Select
                        onValueChange={(value) => field.onChange(value ? Number(value) : undefined)}
                        value={field.value ? String(field.value) : undefined}
                      >
                        <FormControl>
                          <SelectTrigger>
                            <SelectValue placeholder="选择家长" />
                          </SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          {renderParentOptions()}
                        </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                
                <DialogFooter>
                  <Button 
                    type="button" 
                    variant="outline" 
                    onClick={() => setIsAddDialogOpen(false)}
                  >
                    取消
                  </Button>
                  <Button type="submit" disabled={loading}>
                    {loading ? '提交中...' : '添加'}
                  </Button>
                </DialogFooter>
              </form>
            </Form>
          </DialogContent>
        </Dialog>
        
        {/* 编辑学生对话框 */}
        <Dialog open={isEditDialogOpen} onOpenChange={setIsEditDialogOpen}>
          <DialogContent className="sm:max-w-[500px]">
            <DialogHeader>
              <DialogTitle>编辑学生</DialogTitle>
              <DialogDescription>
                修改学生信息，带 * 为必填项
              </DialogDescription>
            </DialogHeader>
            
            <Form {...editForm}>
              <form onSubmit={editForm.handleSubmit(handleEditStudent)} className="space-y-4">
                <FormFieldUI
                  control={editForm.control}
                  name="name"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>姓名 *</FormLabel>
                      <FormControl>
                        <Input {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                
                <FormFieldUI
                  control={editForm.control}
                  name="gender"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>性别 *</FormLabel>
                      <Select
                        onValueChange={field.onChange}
                        defaultValue={field.value}
                      >
                        <FormControl>
                          <SelectTrigger>
                            <SelectValue placeholder="选择性别" />
                          </SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          <SelectItem value="男">男</SelectItem>
                          <SelectItem value="女">女</SelectItem>
                        </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                
                <FormFieldUI
                  control={editForm.control}
                  name="birthday"
                  render={({ field }) => (
                    <FormItem className="flex flex-col">
                      <FormLabel>出生日期</FormLabel>
                      <Popover>
                        <PopoverTrigger asChild>
                          <FormControl>
                            <Button
                              variant="outline"
                              className={cn(
                                "w-full pl-3 text-left font-normal",
                                !field.value && "text-muted-foreground"
                              )}
                            >
                              {field.value ? (
                                format(field.value, "yyyy年MM月dd日", { locale: zhCN })
                              ) : (
                                <span>选择出生日期</span>
                              )}
                              <CalendarIcon className="ml-auto h-4 w-4 opacity-50" />
                            </Button>
                          </FormControl>
                        </PopoverTrigger>
                        <PopoverContent className="w-auto p-0" align="start">
                          <div className="p-3">
                            <Calendar
                              mode="single"
                              selected={field.value}
                              onSelect={field.onChange}
                              disabled={(date) =>
                                date > new Date() || date < new Date("1900-01-01")
                              }
                              initialFocus
                              locale={zhCN}
                              captionLayout="dropdown"
                              fromYear={1900}
                              toYear={new Date().getFullYear()}
                              ISOWeek
                              classNames={{
                                caption_label: "text-sm font-medium",
                                table: "w-full border-collapse space-y-1",
                                head_row: "flex",
                                head_cell: "text-muted-foreground rounded-md w-9 font-normal text-[0.8rem]",
                                row: "flex w-full mt-2",
                                cell: "h-9 w-9 text-center text-sm p-0 relative [&:has([aria-selected])]:bg-accent first:[&:has([aria-selected])]:rounded-l-md last:[&:has([aria-selected])]:rounded-r-md focus-within:relative focus-within:z-20",
                                day: "h-9 w-9 p-0 font-normal aria-selected:opacity-100 rounded-md",
                                day_selected: "bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground focus:bg-primary focus:text-primary-foreground",
                                day_today: "bg-accent text-accent-foreground",
                                day_disabled: "text-muted-foreground opacity-50",
                                day_range_middle: "aria-selected:bg-accent aria-selected:text-accent-foreground",
                                day_hidden: "invisible",
                                nav: "hidden",
                                nav_button: "hidden",
                                nav_button_previous: "hidden",
                                nav_button_next: "hidden",
                              }}
                            />
                          </div>
                        </PopoverContent>
                      </Popover>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormFieldUI
                  control={editForm.control}
                  name="classId"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>班级</FormLabel>
                      <Select
                        onValueChange={(value) => field.onChange(value ? Number(value) : undefined)}
                        value={field.value ? String(field.value) : undefined}
                      >
                        <FormControl>
                          <SelectTrigger>
                            <SelectValue placeholder="选择班级" />
                          </SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          {renderClassOptions()}
                        </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormFieldUI
                  control={editForm.control}
                  name="parentId"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>家长</FormLabel>
                      <Select
                        onValueChange={(value) => field.onChange(value ? Number(value) : undefined)}
                        value={field.value ? String(field.value) : undefined}
                      >
                        <FormControl>
                          <SelectTrigger>
                            <SelectValue placeholder="选择家长" />
                          </SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          {renderParentOptions()}
                        </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                
                <DialogFooter>
                  <Button 
                    type="button" 
                    variant="outline" 
                    onClick={() => setIsEditDialogOpen(false)}
                  >
                    取消
                  </Button>
                  <Button type="submit" disabled={loading}>
                    {loading ? '提交中...' : '保存'}
                  </Button>
                </DialogFooter>
              </form>
            </Form>
          </DialogContent>
        </Dialog>
        
        {/* 删除确认对话框 */}
        <Dialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
          <DialogContent className="sm:max-w-[425px]">
            <DialogHeader>
              <DialogTitle>删除学生</DialogTitle>
              <DialogDescription>
                您确定要删除学生 "{selectedStudent?.name}" 吗？此操作不可撤销。
              </DialogDescription>
            </DialogHeader>
            <DialogFooter>
              <Button 
                type="button" 
                variant="outline" 
                onClick={() => setIsDeleteDialogOpen(false)}
              >
                取消
              </Button>
              <Button 
                type="button" 
                variant="destructive" 
                onClick={handleDeleteStudent}
                disabled={loading}
              >
                {loading ? '删除中...' : '确认删除'}
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
      </div>
    </FadeIn>
  );
} 